<template>
  <div class="w-full h-full box-border bg-[#fff] flex justify-between items-center border-top">
    <div class="ml-[10px]">
      <el-icon class="!text-[30px] cursor-pointer" @click="handleClick"><Picture /></el-icon>
      <input
        ref="fileRef"
        :multiple="false"
        type="file"
        accept="image/*"
        class="hidden"
        @change="handleUpload"
      />
    </div>
    <div class="flex-[1] w-0 ml-[15px]">
      <el-input
        v-model="content"
        type="textarea"
        :rows="3"
        placeholder="输入消息"
        @keydown="handleKeydown"
        @paste="handlePaste"
      />
    </div>
    <div class="ml-[10px]">
      <el-popover popper-class="emoji-popper" placement="top" :width="352" trigger="click">
        <template #reference>
          <el-icon class="!text-[35px] hover:text-[#0087b4] cursor-pointer">
            <Emoji16Regular />
          </el-icon>
        </template>
        <EmojiList @select="handleEmojiClick" />
      </el-popover>
    </div>
    <div class="ml-[10px]">
      <el-tooltip content="快捷回复" placement="top">
        <el-icon
          class="!text-[30px] hover:text-[#0087b4] cursor-pointer"
          v-popover="popoverRef"
          v-click-outside="onClickOutside"
        >
          <ChatLineSquare />
        </el-icon>
      </el-tooltip>
      <el-popover ref="popoverRef" placement="top" :width="240" trigger="click">
        <template #default>
          <div class="h-[300px] flex flex-col justify-between">
            <el-input
              v-model="title"
              placeholder="搜索标题"
              prefix-icon="Search"
              @input="handleSearch"
            />
            <div class="grow-[1] h-0 overflow-hidden">
              <el-scrollbar class="w-full h-full overflow-hidden">
                <template v-for="item in list">
                  <el-tooltip :content="item.Content" placement="left">
                    <div class="reply-item" @click="handleClickReply(item)">{{ item.Title }}</div>
                  </el-tooltip>
                </template>
              </el-scrollbar>
            </div>
            <div
              class="text-[#0087b4] py-[5px] pt-[10px] border-top cursor-pointer"
              @click="handleJump"
            >
              编辑快捷回复...
            </div>
          </div>
        </template>
      </el-popover>
    </div>
    <div class="flex mx-[15px]">
      <el-button type="primary" class="!px-[20px]" round @click="handleSend"> 发送 </el-button>
    </div>
    <SendImgDialog
      ref="sendImgDialogRef"
      :src="clipBoardState.src"
      :file="clipBoardState.file"
      @close="handleClose"
      @upload="(img: string) => emit('upload', img)"
    />
  </div>
</template>
<script lang="ts" setup>
import EmojiList from "@/components/emoji-list.vue";
import SendImgDialog from "./send-img.dialog.vue";

import { ref } from "vue";
import { Emoji16Regular } from "@vicons/fluent";
import { debounce } from "lodash-es";
import { reqUploadImg } from "@/api/user";
import { ClickOutside as vClickOutside } from "element-plus";
import { reqReplyList } from "@/api/setting";
import { message } from "@/utils/message";

const popoverRef = ref();
const fileRef = ref();
const sendImgDialogRef = ref();
const router = useRouter();
const content = ref("");
const title = ref("");
const list = ref<ReplyMo[]>([]);
const emit = defineEmits(["send", "upload"]);
const clipBoardState = reactive({
  src: "",
  file: <File | null>null
});

const handleSend = debounce(() => {
  if (!content.value) {
    message.warning("请输入消息");
    return;
  }
  emit("send", content.value);
  content.value = "";
}, 0);

const onClickOutside = () => {
  unref(popoverRef).popperRef?.delayHide?.();
};

const handleClick = () => {
  fileRef.value.click();
};

const handleEmojiClick = (e: any) => {
  content.value += e;
};

const handleClickReply = (e: ReplyMo) => {
  content.value += e.Content;
};

const handleUpload = async (ev: any) => {
  if (ev.target.files[0]) {
    try {
      let param = new FormData();
      param.append("ImgPath", ev.target.files[0]);
      const res = await reqUploadImg(param);
      emit("upload", res.data.ImgPath);
    } catch (error) {
      console.log(error);
    }
  }
};

const handleJump = () => {
  router.push("/admin/setting/reply");
};

const getList = async () => {
  try {
    const res = await reqReplyList({
      Page: 1,
      PageSize: 199,
      ...(title.value ? { Title: title.value } : {})
    });
    list.value = res.data.List;
  } catch (error) {
    console.log(error);
  }
};

const handleSearch = debounce(() => {
  getList();
}, 700);

// 处理回车事件
const handleKeydown = (event: KeyboardEvent) => {
  // 判断是 Ctrl + Enter (Windows/Linux) 或 Cmd + Enter (Mac)
  if ((event.key === "Enter" && event.ctrlKey) || (event.key === "Enter" && event.metaKey)) {
    // 当按下 Ctrl + Enter 或 Cmd + Enter 时，插入换行符
    content.value += "\n"; // 在 textarea 中添加换行
    event.preventDefault(); // 阻止默认行为（不提交表单）
  } else if (event.key === "Enter") {
    // 仅按下 Enter 键时，不进行换行
    event.preventDefault(); // 阻止 Enter 默认的换行行为
    handleSend();
  }
};

// 处理剪切版
const handlePaste = (event: ClipboardEvent): void => {
  const clipboardItems = event.clipboardData?.items;
  if (!clipboardItems) return;

  for (const item of clipboardItems) {
    if (item.type.startsWith("image/")) {
      const file = item.getAsFile();
      if (file) {
        const reader = new FileReader();
        reader.onload = (e: ProgressEvent<FileReader>) => {
          if (e.target?.result) {
            clipBoardState.src = e.target.result as string;
            clipBoardState.file = file;
            nextTick(() => {
              sendImgDialogRef.value?.open();
            });
          }
        };
        reader.readAsDataURL(file);
      }
      break;
    }
  }
};

const handleClose = () => {
  clipBoardState.src = "";
  clipBoardState.file = null;
};

onMounted(() => {
  getList();
});
</script>
<style>
.emoji-popper {
  padding: 0 !important;
  border-radius: 8px !important;
}
</style>
<style lang="scss" scoped>
.el-textarea {
  --el-input-bg-color: #f9f9f9;
}
.el-button {
  padding: 13px 20px;
}
.reply-item:first-child {
  margin-top: 6px;
}
.reply-item {
  cursor: pointer;
  padding: 10px;
  margin: 0 5px;
  font-size: 14px;
  margin-bottom: 6px;
  box-shadow: 0px 0px 5px 2px rgba(0, 0, 0, 0.05);
}
</style>
